/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Model;

import java.util.Collections;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import javax.persistence.PersistenceException;
import javax.persistence.Query;
import javax.swing.JOptionPane;

public class CustomerDAO {

    private static EntityManager em;
    private static EntityTransaction tx;

    public CustomerDAO() {
        em = getEntityManager();
        tx = em.getTransaction();
    }

    public void addCustomer(Customer customer) {

        try {
            tx.begin();
            em.persist(customer);
            tx.commit();
        } catch (PersistenceException e) {
            System.out.println("no se agrego");
        } finally {
        }
    }

    public void editCostumer(Customer cust) {
        try {
            tx.begin();
            em.merge(cust);
            tx.commit();
         
        } catch (PersistenceException e) {
           
        } finally {
        }
    }

    public void deleteCostumer(String id) {

        try {
            
            tx.begin();
            em.remove(getCustomer(id));
            tx.commit();
            
        } catch (PersistenceException e) {
            
        } finally {
        }
    }

    public Customer getCustomer(String id) {
        return (Customer) em.find(Customer.class, id);
    }

    public List<Customer> getAllCustomer() {
        Query query = em.createNamedQuery("getAll");
        
        List <Customer>list =query.getResultList();
   
        Collections.sort(list);
        return list;
        
    }

    public static EntityManager getEntityManager() {
        if (em == null) {
            em = Persistence.createEntityManagerFactory("FormularioPU").createEntityManager();
        }
        return em;
    }
}
